const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const glob = require('glob');
const webpack = require('webpack')
const CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");//有问题，有时间再研究


const entries = getEntry('src/assets/js/**/*.js');
const commonsChunk = getCommonsChunk('src/assets/js/common/**/*.js');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const devMode = true;

function resolve(dir){
  console.log("---dirname---"+__dirname+"----result----"+path.join(__dirname, dir))
  return path.join(__dirname, dir);
}


const config = {
  entry: entries,
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'js/[name].js'    
  }, 
  resolve: {
    extensions: ['.js', '.css', '.html','.png'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src')
    }
  },  
  mode: 'development',
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /\.(scss)$/,
        use: [{
          loader: 'style-loader', // inject CSS to page
        }, {
          loader: 'css-loader', // translates CSS into CommonJS modules
        }, {
          loader: 'postcss-loader', // Run post css actions
          options: {
            plugins: function () { // post css plugins, can be exported to postcss.config.js
              return [
                require('precss'),
                require('autoprefixer')
              ];
            }
          }
        }, {
          loader: 'sass-loader' // compiles Sass to CSS
        }]
      }, 


      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          // "style-loader",
          "css-loader"
        ]      
      },    
      {
        test: /\.(jpg|gif|png|ico)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      },
      {
        test: /\.(htm|html)$/i,
        use:[ 'html-withimg-loader'] 
      },
      {
          test: require.resolve('jquery'),
          use: [{
            loader: 'expose-loader',
            options: '$'
         }]
      }      
    ]
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      filename: 'index.html',
      // loader: "raw-loader",
      template: 'index.html',
      chunks:['index','common'],
      inject: 'body',
      favicon: './favicon.ico'     
    }),
    new CommonsChunkPlugin({
            name: 'common', // 将公共模块提取，生成名为`vendors`的chunk
            chunks: commonsChunk //提取哪些模块共有的部分
            // minChunks: commonsChunk.length // 提取至少3个模块共有的部分
        }),    
    new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      path: path.resolve(__dirname, 'dist'),
      filename: "css/[name].css",
      // chunkFilename: "[id].css"
    }),
    // bootatrap4 配置，引入jquery、popper，页面无需再引这两个 by litian
    new webpack.ProvidePlugin({
        $: 'jquery',
        jQuery: 'jquery',
        'window.jQuery': 'jquery',
        Popper: ['popper.js', 'default']
      }) ,
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, './static'),
        to: 'static',
        ignore: ['.*']
      }
    ])  
  ],  
  devServer: {
    contentBase: './dist',
    port:'8088'
  },
};

const viewsObj = getView("src/view/page/**/*.html","src/view");
const pages = Object.keys(viewsObj);
pages.forEach(function(pathname){
    var htmlName = viewsObj[pathname]
    var conf = {
        filename: './view/page/' + htmlName + '.html', //生成的html存放路径，相对于path
        template: './src/view/page/' + htmlName + '.html', //html模板路径
        inject: 'body', //js插入的位置，true/'head'/'body'/false
        hash: true, //为静态资源生成hash值
        // favicon: './src/img/favicon.ico', //favicon路径，通过webpack引入同时可以生成hash值
        chunks: [htmlName,'common'],//需要引入的chunk，不配置就会引入所有页面的资源
        minify: { //压缩HTML文件    
            removeComments: true, //移除HTML中的注释
            collapseWhitespace: false //删除空白符与换行符
        }
    };
    config.plugins.push(new HtmlWebpackPlugin(conf));
})


module.exports = config;

function getView(globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    var baseDirname = path.join('src','view');
    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        
        dirname = path.dirname(entry);
        
        extname = path.extname(entry);
        
        basename = path.basename(entry, extname);

        pathname = path.join(dirname, basename);
        pathname = pathDir ? pathname.replace(new RegExp('^' + pathDir), '') : pathname;
        entries[pathname] =  basename;
    }
    console.log('-------------123------------'+JSON.stringify(entries))
    return entries;
}

function getEntry(globPath) {
    var files = glob.sync(globPath);//以同步方式，得到globPath下的所有文件，glob，可通过类似正则表达式的方式取到目录下的所有文件，sync同步
    var entries = {},
        entry, basename, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        extname = path.extname(entry);//返回后缀
        basename = path.basename(entry, extname);//反回路径中的最后一部分
        entries[basename] = './' + entry;
    }
    // entries.bootstrap='bootstrap-loader';
    console.log("------entries-----"+JSON.stringify(entries));

    return entries;
}

function getCommonsChunk(globPath) {
    var files = glob.sync(globPath);
    var entries = [],
        entry, dirname, basename, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        entries.push(basename);
    }

    console.log('--------commonsChunk------'+entries)
    return entries;
}